package com.jiangnanxiaoguan.controller;

import com.jiangnanxiaoguan.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.nio.file.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.UUID;

/**
 * @author 不愿透露姓名的狂热者
 * @version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${jiangnanxiaoguan.path}")
    private String basePath;

    @PostMapping("upload")
    public Result<String> upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        log.info("[文件上传]：{}", originalFilename);

        // 原文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        // 生成下载文件夹
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        String directoryPath = simpleDateFormat.format(date);

        // 生成新的文件名，以防重名覆盖掉原图片
        String newFileName = UUID.randomUUID() + suffix;

        // 创建图片下载文件夹
        String downloadDirPath = basePath + directoryPath;
        File downloadDirectory = new File(downloadDirPath);

        if (downloadDirectory.mkdirs())
            log.info("文件夹：{} 创建成功", downloadDirectory.getPath());

        // 转存
//        File downloadFile = new File("D:/" + downloadDirectory.getPath() + "/" + newFileName);
        File downloadFile = new File(downloadDirectory.getPath() + "/" + newFileName);
//        file.transferTo(downloadFile);

        /*
            修复File无法寻找项目所在盘符问题（主要针对Windows）
         */
        FileOutputStream fileOutputStream = new FileOutputStream(downloadFile);
        fileOutputStream.write(file.getBytes());
        fileOutputStream.close();

        log.info("下载的图片路径：{}", downloadFile.getPath());

        // 前端用于请求下载图片
        return Result.success(directoryPath + "/" + newFileName);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
        String filePath = basePath + name;
        log.info("图片路径：{}", filePath);

        // 原生IO流读取
        FileInputStream fileInputStream = new FileInputStream(filePath);
        // 边读边向浏览器发送数据
        int readByteLen = 0;
        byte[] bytes = new byte[8192];
        ServletOutputStream outputStream = response.getOutputStream();
        while ((readByteLen = fileInputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, readByteLen);
        }

        // 关闭内存资源的占用
        outputStream.close();
        fileInputStream.close();
    }
}
